package other;

/**
 * Created by lyyn on 2022/9/14.
 */
//题意：删除链表中等于给定值 val 的所有节点。
//
//        示例 1：
//        输入：head = [1,2,6,3,4,5,6], val = 6
//        输出：[1,2,3,4,5]
//
//        示例 2：
//        输入：head = [], val = 1
//        输出：[]
//
//        示例 3：
//        输入：head = [7,7,7,7], val = 7
//        输出：[]
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class RemoveElements_203 {
    public ListNode removeElements(ListNode head, int val) {
        while (head != null && head.val == val){
            head = head.next;
        }
        if(head == null){
            return head;
        }
        ListNode l = head;
        while (l.next != null){
            if(l.next.val == val){
                l.next = l.next.next;
            }else {
                l = l.next;
            }
        }
        return head;
    }
    public ListNode removeElements_1(ListNode head, int val) {
        if(head == null){
            return head;
        }
        ListNode newHead = new ListNode(-1,head);
        ListNode l = newHead;
        while (l.next != null){
            if(l.next.val == val){
                l.next = l.next.next;
            }else {
                l = l.next;
            }
        }
        return newHead.next;
    }
}
